<template>
  <div class="visit-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑拜访' : '新增拜访' }}</h3>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="form.customerId"
            filterable
            remote
            :remote-method="searchCustomers"
            placeholder="请选择客户"
            style="width: 100%"
            :loading="loading"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="拜访日期" prop="visitDateStr">
          <el-date-picker
            v-model="form.visitDateStr"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="拜访类型" prop="visitType">
          <el-select v-model="form.visitType" placeholder="请选择拜访类型" style="width: 100%">
            <el-option
              v-for="[value, { label }] in Object.entries(VisitTypeMap)"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="拜访主题" prop="title">
          <el-input v-model="form.title" placeholder="请输入拜访主题" />
        </el-form-item>

        <el-form-item label="拜访地点" prop="visitAddress">
          <el-input v-model="form.visitAddress" placeholder="请输入拜访地点" />
        </el-form-item>

        <el-form-item label="拜访协同人" prop="collaboratorIds">
          <el-select
            v-model="form.collaboratorIds"
            multiple
            filterable
            placeholder="请选择协同人"
            style="width: 100%"
          >
            <el-option
              v-for="item in collaboratorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="拜访目的" prop="visitPurpose">
          <el-input
            v-model="form.visitPurpose"
            type="textarea"
            :rows="2"
            placeholder="请输入拜访目的"
          />
        </el-form-item>

        <el-form-item label="拜访内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入拜访内容" />
        </el-form-item>

        <el-form-item label="拜访结果" prop="visitResult">
          <el-input
            v-model="form.visitResult"
            type="textarea"
            :rows="3"
            placeholder="请输入拜访结果"
          />
        </el-form-item>

        <el-form-item label="后续计划" prop="nextPlan">
          <el-input
            v-model="form.nextPlan"
            type="textarea"
            :rows="3"
            placeholder="请输入后续计划"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { VisitType, VisitTypeMap } from '@/types/visit'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createVisit, updateVisit, getVisit } from '@/api/visit'
import { searchCustomers as searchCustomersApi } from '@/api/customer'
import { getDepartmentUsers } from '@/api/department'
import type { Visit } from '@/types/visit'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const customerOptions = ref<{ id: number; name: string }[]>([])
const collaboratorOptions = ref<{ id: number; name: string }[]>([])
const loading = ref(false)

const form = reactive<
  Omit<Visit, 'visitType' | 'visitTime'> & {
    visitType: VisitType
    visitTime?: number
    visitDateStr: string
  }
>({
  customerId: null as unknown as number,
  title: '',
  visitDateStr: '',
  visitType: VisitType.PHONE_CALL,
  visitPurpose: '',
  visitAddress: '',
  content: '',
  visitResult: '',
  nextPlan: '',
  collaboratorIds: [],
})

const rules = reactive<FormRules>({
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  title: [{ required: true, message: '请输入拜访主题', trigger: 'blur' }],
  visitDateStr: [{ required: true, message: '请选择拜访日期', trigger: 'change' }],
  visitType: [{ required: true, message: '请选择拜访类型', trigger: 'change' }],
  visitPurpose: [{ required: true, message: '请输入拜访目的', trigger: 'blur' }],
  visitAddress: [{ required: true, message: '请输入拜访地点', trigger: 'blur' }],
  content: [{ required: true, message: '请输入拜访内容', trigger: 'blur' }],
  visitResult: [{ required: true, message: '请输入拜访结果', trigger: 'blur' }],
  nextPlan: [{ required: true, message: '请输入后续计划', trigger: 'blur' }],
})

const timestampToDateString = (timestamp: number): string => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const dateStringToTimestamp = (dateStr: string): number => {
  return new Date(dateStr + ' 00:00:00').getTime()
}

const loadCollaborators = async () => {
  try {
    const user = localStorage.getItem('user')
    if (!user) {
      throw new Error('用户未登录')
    }
    const userData = JSON.parse(user)
    const departmentId = userData.departmentId
    if (!departmentId) {
      throw new Error('用户部门信息缺失')
    }
    const res = await getDepartmentUsers(departmentId)
    collaboratorOptions.value = res.data.map((user) => ({
      id: user.id,
      name: user.username,
    }))
  } catch (error) {
    console.error('加载协同人失败:', error)
    ElMessage.error('加载协同人失败')
  }
}

const searchCustomers = async (query: string) => {
  if (query && query.trim()) {
    try {
      const res = await searchCustomersApi(query)
      customerOptions.value = res.data
    } catch (error) {
      console.error('搜索客户失败:', error)
      ElMessage.error('搜索客户失败')
    }
  } else {
    customerOptions.value = []
  }
}

const loadVisitData = async (id: number) => {
  try {
    const res = await getVisit(id)
    const visitData = res.data

    if (visitData.visitTime) {
      form.visitDateStr = timestampToDateString(visitData.visitTime)
    }

    Object.assign(form, {
      ...visitData,
      visitTime: visitData.visitTime,
    })

    if (visitData.customerId && visitData.customerName) {
      customerOptions.value = [
        {
          id: visitData.customerId,
          name: visitData.customerName,
        },
      ]
    }
  } catch (error) {
    console.error('加载拜访数据失败:', error)
    ElMessage.error('加载拜访数据失败')
  }
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const finalSubmitData = {
          customerId: form.customerId,
          title: form.title,
          visitTime: dateStringToTimestamp(form.visitDateStr),
          visitType: form.visitType,
          visitPurpose: form.visitPurpose,
          visitAddress: form.visitAddress,
          content: form.content,
          visitResult: form.visitResult,
          nextPlan: form.nextPlan,
          collaboratorIds: form.collaboratorIds,
        }

        if (isEdit.value) {
          await updateVisit(Number(route.params.id), finalSubmitData)
          await axios.post('/api/logs', {
            action: 'UPDATE_VISIT',
            description: `更新拜访记录：${form.title}`,
          })
          ElMessage.success('更新成功')
        } else {
          await createVisit(finalSubmitData)
          await axios.post('/api/logs', {
            action: 'CREATE_VISIT',
            description: `创建拜访记录：${form.title}`,
          })
          ElMessage.success('创建成功')
        }
        goBack()
      } catch (error) {
        console.error('保存拜访记录失败:', error)
        ElMessage.error('保存拜访记录失败')
      }
    }
  })
}

const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: isEdit.value ? '访问编辑拜访页面' : '访问创建拜访页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

const goBack = () => {
  router.push('/visits')
}

onMounted(() => {
  const id = route.params.id
  if (id) {
    isEdit.value = true
    loadVisitData(Number(id))
  }
  loadCollaborators()
  recordPageAccess()
})
</script>

<style scoped>
.visit-form {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
